package com.litree.service.utils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class HandlerLoginFilter implements HandlerInterceptor {
	private List<String> excludedUrls;

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }
    private static final Logger logger = LoggerFactory.getLogger(HandlerLoginFilter.class);
    
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String requestUri = request.getRequestURI();
        for (String url : excludedUrls) {
            if (requestUri.startsWith(url)) {
            	if(!requestUri.contains("image") &&
            	!requestUri.contains("updatePw")){
            		return true;            		
            	}
            }
        }
        
        // intercept
        Map tokenMap = getTokenInfo(request, response, logger);
        if(!tokenMap.isEmpty()){
        	request.setAttribute("tokenMap", tokenMap);
	    	return true;
	    }else{
	    	return false;
	    }
	}
	
	/**
	 * get info from HTTP header
	 * @param request
	 * @return
	 */
	protected Map<String, String> getHeadersInfo(HttpServletRequest request) {
	    Map<String, String> map = new HashMap<String, String>();
	    Enumeration headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	        String key = (String) headerNames.nextElement();
	        String value = request.getHeader(key);
	        map.put(key, value);
	    }
	    return map;
	}
	

	private Map getTokenInfo(HttpServletRequest request,HttpServletResponse response,Logger logger) {
		Map reslutMap = new HashMap();
		try{			
			Map headerInfo = getHeadersInfo(request);
			if(headerInfo != null){
				String token = headerInfo.get("token") ==null?"":headerInfo.get("token").toString();
				if(!"".equals(token)){
					String[] tokenDecode = CommonUtils.decrypt(token).split(",");
					if(tokenDecode.length != 2){
						ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+" token error!");
					}else{
						reslutMap.put("loginName",tokenDecode[0]);
						reslutMap.put("createTokenTime",tokenDecode[1] );
					}
				}else{
					ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+" not found token in header!");
				}
			}else{
				ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+" header is null!");
			}
		}catch(Exception e){
			try {
				ReturnMSGUtils.sentMsgWithCause(response, "0", ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+"token error!", e.toString());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			logger.error(CommonUtils.errMsg(ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+"token error!", e));
		}
		return reslutMap;
	}

}
